<template>
  <div  class="scanner" >
      <qrcode-stream  @track="paintBoundingBox" @detect="onDetect"  @error="onError"></qrcode-stream>
  </div>
</template>

<script setup>
  import { ref,defineEmits} from 'vue'
  import {QrcodeStream} from 'vue-qrcode-reader'
  defineProps({
    msg: String,
  })
  
  const result = ref('')
  const error = ref('')
  
  const paintBoundingBox = (detectedCodes, ctx)=>{
    for (const detectedCode of detectedCodes) {
      const {
        boundingBox: {
          x,
          y,
          width,
          height
        }
      } = detectedCode
  
      ctx.lineWidth = 2
      ctx.strokeStyle = '#007bff'
      ctx.strokeRect(x, y, width, height)
    }
  }
  
  const onError = (err) =>{
    error.value = `[${err.name}]: `
  
    if (err.name === 'NotAllowedError') {
      error.value += 'you need to grant camera access permission'
    } else if (err.name === 'NotFoundError') {
      error.value += 'no camera on this device'
    } else if (err.name === 'NotSupportedError') {
      error.value += 'secure context required (HTTPS, localhost)'
    } else if (err.name === 'NotReadableError') {
      error.value += 'is the camera already in use?'
    } else if (err.name === 'OverconstrainedError') {
      error.value += 'installed cameras are not suitable'
    } else if (err.name === 'StreamApiNotSupportedError') {
      error.value += 'Stream API is not supported in this browser'
    } else if (err.name === 'InsecureContextError') {
      error.value += 'Camera access is only permitted in secure context. Use HTTPS or localhost rather than HTTP.'
    } else {
      error.value += err.message
    }
  }
  
  const emit = defineEmits(['scan']);

  const onDetect  = (detectedCodes) => {
    result.value = detectedCodes.map((code) => code.rawValue);
    
    if(result.value.length && result.value.length > 0){
      emit('scan', result.value[0]);  
    }
    
  } 
  
  
</script>

<style scoped lang="scss">
  .scanner{
    width: 100vw;
    height: 100%;
    position: absolute;
    left: 0;
    top: 0;
    .result{
      color: #000000;
      font-size: 30px;
    }
  }
</style>